package com.example.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import com.example.constant.ClientConstants;
import com.google.gson.Gson;

/**
 * TCP发送、接收数据
 * @author zyh
 *
 */
public class TcpRequestController {
	
	public static <T> T GetResultByParam(T Request,T Result,String ip,int port)
	{
		Gson son = new Gson();
		String key = ClientConstants.key;
		String json;
		Socket client = null;
		InputStream in = null;
		OutputStream out = null;
		try {
			json = Des.encryptDES(son.toJson(Request), key, key);
			client = new Socket(ip, port);
			in = client.getInputStream();
			out = client.getOutputStream();
			out.write(json.getBytes()); // 发送注册数据
			byte[] buf = new byte[300]; // 接收返回数据
			int len = in.read(buf);
			out.close();
			in.close();
			client.close();
			out = null;
			in = null;
			client = null;
			String res = new String(buf, 0, len);
			if (res != null && !res.equals("")) {
				return (T) DataBuilder.buildObject(
						Des.decryptDES(res, key, key), Result);
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} finally {
			try {
				if (out != null)
					out.close();
				if (in != null)
					in.close();
				if (client != null)
					client.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}
}
